package com.test.study.shiro_demo.controller;


import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.*;
import org.apache.shiro.subject.Subject;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class MyController {

    @GetMapping("login")
    public String GetLoginPage(){
        return "login";
    }
    @GetMapping("index")
    public String GetIndex(){
        return "index";
    }
    @PostMapping("userLogin")
    public  String GetUserLogin(String uname,String pwd,@RequestParam(defaultValue = "false") Boolean remember){
        if (remember==null){
            remember=false;
        }
        System.out.println(uname+","+pwd+" , "+remember);
        //获取subject对象
        Subject subject= SecurityUtils.getSubject();
        //创建对象认证信息

        UsernamePasswordToken token = new UsernamePasswordToken(uname, pwd,remember);
        //调用shiro的login方法完成登录
        try {
            subject.login(token);
            return "redirect:/index";
        } catch (UnknownAccountException e) {
            e.printStackTrace();
            System.out.println("用户错误！");
        } catch (IncorrectCredentialsException e){
            System.out.println("密码错误");
        }catch (ExcessiveAttemptsException e){
            System.out.println("登录次数过多，锁定10分钟");
        }
        return "redirect:/login";
    }

    @RequestMapping("logout")
    public String logout( ) {
        Subject subject = SecurityUtils.getSubject();
        subject.logout();
        System.out.println("已退出！");
        return "redirect:/login";
    }
}
